package com.zrrd.learn.framework.mybatis.mybatisinterface;

import com.zrrd.learn.framework.mybatis.mybatisinterface.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 注解开发模式，接口+注解
 *
 * @author wrn
 * @version 1.0
 * @date 2023/9/1 11:08
 */

public class Demo02 {

    private final String resource = "mybatisconfiguration.xml";

    public SqlSession getSqlSession() {
        InputStream inputStream = null;
        try {
            //把mybatisconfiguration里面的信息读取到java里面
            inputStream = Resources.getResourceAsStream(resource);

            //建造者模式  [把xml里面的文本信息读取java并为大量的java类完成初始化赋値]
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
            //把你想要处理的mapper存储到factory
            sqlSessionFactory.getConfiguration().addMapper(StudentMapper.class);

            SqlSession ss = sqlSessionFactory.openSession(true);
            return ss;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用来调用 mapper 里面的查询全部
     *
     * @return
     */
    public List<Map<String, Object>> te1() {

        //动态代理 把自动给接口生成一个作为实例

        //从工厂生成的实例当中找到StudentMapper的实例给你返回
        StudentMapper sm = getSqlSession().getMapper(StudentMapper.class);
        return sm.showAll();
    }

    public int add(String stu_name, String stu_sex, String xueli) {
        SqlSession ss = getSqlSession();
        int n = 0;
        try{
            StudentMapper sm = ss.getMapper(StudentMapper.class);
            n = sm.addStudent(stu_name, stu_sex, xueli);
            ss.commit();
        }catch (Exception e){
            ss.rollback();
        }
        return n;
    }

    public static void main(String[] args) {
        Demo02 demo02 = new Demo02();

        int add = demo02.add("admin", "男", "博士");
        System.out.println(add);
//        demo02.te1().forEach(System.out::println);
//
//        System.out.println("------");
//        List<Map<String, Object>> list = demo02.te1();
//        for (int i = 0; i < list.size(); i++) {
//            System.out.println(list.get(i).get("stu_name"));
//        }

    }


}